import axios from 'axios';
import {notification, message} from 'antd';
import NProgress from 'nprogress';

const request = axios.create({
    timeout: 15000, // // 超时时间
    // headers: {
    //     'Content-Type': 'application/json; charset=UTF-8',
    // },
});

request.interceptors.request.use(
    (config) => {
        const {
            method = 'POST',
            data = {},
        } = config;
        // 没有特殊配置，则自动显示加载中loading
        NProgress.start();
        config.data = method === 'post' ? data : '';
        config.params = method === 'get' ? data : '';
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
);
request.interceptors.response.use((response) => {
        NProgress.done();
        const res = response.data;
        const code = res.code;
        switch (code) {
            case 0:
            case 200:
                return Promise.resolve(res);
            case 303:
                message.info('登录失效');
                return Promise.reject(res);
            case 400:
                notification.error({
                    message: '请求错误',
                    description: res.message || res.data.message || '网络超时,请重新登录',
                });
                return Promise.reject(res);
            case 401:
                notification.error({
                    message: '请求错误',
                    description: res.message || res.data.message || '验证过期',
                });
                return Promise.reject(res);
            case 404:
                notification.error({
                    message: '请求错误',
                    description: res.message || res.data.message || '请求地址无效',
                });
                return Promise.reject(res);
            case 500:
                notification.error({
                    message: '请求错误',
                    description: res.message || res.data.message || '服务器内部错误',
                });
                return Promise.reject(res);
            case 503:
                notification.error({
                    message: '请求错误',
                    description: res.message || res.data.message || '服务器连接失败',
                });
                return Promise.reject(res);
            default:
                notification.error({
                    message: '请求错误',
                    description: res.message || res.data.message || '网络异常',
                });
                return Promise.reject(res);
        }
    },
    () => {
        NProgress.done();
        // notification.error({
        //     message: '异常错误',
        // });
        // return Promise.resolve(error);
        return Promise.resolve({
            code: 0,
        });
    },
);

export default request;
